<template>

  <div class="ele-body ele-body-card">
    <!-- 顶部统计快 -->
    <!-- 地域选择-->
    <a-card v-if="user.roleId === '2'"
            :bordered="false" :body-style="{padding: 8}" :head-style="{fontSize: '18px'}"
            title="">
      <a-select v-model:value="region" placeholder="地域" allow-clear style="position: absolute; right: 0;width: 100px;margin-right: 25px;margin-top: -15px;">
        <a-select-option v-for="region in regionList" :key="region" :value="region">
          {{ region }}
        </a-select-option>
      </a-select>
    </a-card>

    <a-card :bordered="false" :body-style="{padding: 8}" :head-style="{fontSize: '18px'}"
            title="客户分析">
      <template #extra>
        <a-select v-if="user.agentId !== ''"
                  v-model:value="customerSearch.selectUserId"
                  placeholder="全体销售"
                  @change="reloadCustomer"
                  allowClear
        >
          <a-select-option v-for="agentUser in agentUserList" :key="agentUser.userId" :value="agentUser.userId">
            {{ agentUser.realName }}
          </a-select-option>
        </a-select>

        <a-select
          v-if="user.agentId === ''"
          v-model:value="customerSearch.agentId"
          :placeholder="user.selectPre+'全体代理商'"
          @change="reloadCustomer"
          allowClear
        >
          <a-select-option v-for="agent in agentList" :key="agent.id" :value="agent.id">
            {{ agent.name }}
          </a-select-option>
        </a-select>
      </template>

      <a-row :gutter="16">
        <a-col :lg="11" :md="24" :sm="24" :xs="24">
          <a-tabs size="small" class="monitor-card-tabs">
            <a-tab-pane :tab="'本月统计（' + currentYear + '年' + currentMonth + '月）'" key="thisMonth">
              <a-card title="" :bordered="false" :body-style="{padding: 8}" style="padding: 0 1px">
                <a-card-grid :key="map.name" v-for="(map,index) in customerData.month"
                             class="monitor-count-card">

                  <a-row :gutter="12">
                    <a-col :span="6">
                      <div class="monitor-count-card-left">
                        <ele-tag v-if="index === 0" shape="circle" size="large">
                          <AuditOutlined />
                        </ele-tag>
                        <ele-tag v-if="index === 1" color="success" shape="circle" size="large">
                          <FileProtectOutlined />
                        </ele-tag>
                        <ele-tag v-if="index === 2" color="orange" shape="circle" size="large">
                          <UserAddOutlined />
                        </ele-tag>
                      </div>
                    </a-col>
                    <a-col :span="18">

                      <div class="monitor-count-card-right">
                        <h1 class="monitor-count-card-num">{{ map.number }}</h1>

                        <div class="monitor-count-card-text">{{ map.name }}</div>
                        <div v-if='map.upDown === true' class="monitor-count-card-trend ele-text-success">
                          <span>环比：{{ map.upDownValue }}%</span>
                          <RiseOutlined />
                        </div>
                        <div v-else class="monitor-count-card-trend ele-text-danger">
                          <span>环比：{{ map.upDownValue }}%</span>
                          <FallOutlined />
                        </div>
                      </div>
                    </a-col>
                  </a-row>

                </a-card-grid>
              </a-card>
            </a-tab-pane>
          </a-tabs>
          <a-tabs size="small" class="monitor-card-tabs">
<!--            <a-tab-pane :tab="'本年统计（' + currentYear + '年）'"
                        key="thisYear">-->
            <a-tab-pane key="thisYear">
              <template #tab>
                <span>
                  本年统计（{{ currentYear }}）年
                  <a-popover>
                    <template #content>
                      <p style="margin-top: 15px;">在统计期间内重复客户只统计一次</p>
                    </template>
                    <InfoCircleTwoTone />
                  </a-popover>
                </span>
              </template>

              <!--              <a-row>-->
              <!--                <a-col :key="map.name" :lg="8" :md="12" :sm="24" :xs="24">-->
              <a-card title="" :bordered="false" :body-style="{padding: 8}" style="padding: 0 1px">
                <a-card-grid :key="map.name" v-for="(map,index) in customerData.year"
                             class="monitor-count-card">

                  <a-row :gutter="12">
                    <a-col :span="6">
                      <div class="monitor-count-card-left">
                        <ele-tag v-if="index === 0" shape="circle" size="large">
                          <AuditOutlined />
                        </ele-tag>
                        <ele-tag v-if="index === 1" color="success" shape="circle" size="large">
                          <FileProtectOutlined />
                        </ele-tag>
                        <ele-tag v-if="index === 2" color="orange" shape="circle" size="large">
                          <UserAddOutlined />
                        </ele-tag>
                      </div>
                    </a-col>
                    <a-col :span="18">

                      <div class="monitor-count-card-right">
                        <h1 class="monitor-count-card-num">{{ map.number }}</h1>

                        <div class="monitor-count-card-text">{{ map.name }}</div>
                        <div v-if='map.upDown === true' class="monitor-count-card-trend ele-text-success">
                          <span>环比：{{ map.upDownValue }}%</span>
                          <RiseOutlined />
                        </div>
                        <div v-else class="monitor-count-card-trend ele-text-danger">
                          <span>环比：{{ map.upDownValue }}%</span>
                          <FallOutlined />
                        </div>
                      </div>
                    </a-col>
                  </a-row>
                </a-card-grid>
              </a-card>
              <!--                </a-col>-->
              <!--              </a-row>-->
            </a-tab-pane>
          </a-tabs>
        </a-col>
        <a-col :lg="13" :md="24" :sm="24" :xs="24">
          <a-tabs size="small" class="monitor-card-tabs">
            <a-tab-pane tab="综合统计" key="saleroom">
              <a-row :gutter="16">
                <a-col :lg="24" :md="24" :sm="24" :xs="24">
                  <!--                  <div class="demo-monitor-title">客户数量</div>-->
                  <ele-chart :options="saleChartOption" style="height: 370px;" />
                </a-col>
              </a-row>
            </a-tab-pane>
            <template #tabBarExtraContent>
              <a-space size="small" class="analysis-tabs-extra">
                <a-month-picker @change="reloadCustomerByMonth(1)" placeholder="开始月份"
                                fomat="YYYY-MM"
                                valueFormat="YYYY-MM"
                                :default-value="customerSearch.dataTimeStart"
                                style="width: 100px;margin-right: -5px;"
                                v-model:value="customerSearch.dataTimeStart">
                </a-month-picker>
                -
                <a-month-picker @change="reloadCustomerByMonth(2)" placeholder="结束月份"
                                fomat="YYYY-MM"
                                valueFormat="YYYY-MM"
                                style="width: 100px;margin-left: -5px;"
                                v-model:value="customerSearch.dataTimeEnd">
                </a-month-picker>
                <a-select
                  @change="reloadCustomerByMonth(3)"
                  v-model:value="customerSearch.dataType">
                  <a-select-option value="1" selected>报备客户数</a-select-option>
                  <a-select-option value="2">成交客户数</a-select-option>
                  <a-select-option value="3">新增客户数</a-select-option>
                </a-select>
              </a-space>
            </template>
          </a-tabs>
        </a-col>
      </a-row>

    </a-card>
    <!-- 销售业绩 -->
    <AnalysisSales :region="region"/>
    <AnalysisSeniorityUser :region="region"/>
    <AnalysisSeniorityAgent :region="region" v-if="user.roleId !== '3' && user.roleId !== '4'&& user.roleId !== '5'" />
    <AnalysisSeniorityRegion :region="region"
      v-if="user.roleId !== '2' && user.roleId !== '3' && user.roleId !== '4'&& user.roleId !== '5'" />


  </div>

</template>

<script>
import EleChart from 'ele-admin-pro/packages/ele-chart';
import { DashboardApi } from '@/api/DashboardApi';
import { WebUserApi } from '@/api/WebUserApi';
import moment from 'moment';
import AnalysisSales from '@/views/dashboard/analysis-sales.vue';
import AnalysisSeniorityUser from '@/views/dashboard/analysis-seniority-user.vue';
import AnalysisSeniorityAgent from '@/views/dashboard/analysis-seniority-agent.vue';
import AnalysisSeniorityRegion from '@/views/dashboard/analysis-seniority-region.vue';
import { AgentApi } from '@/api/AgentApi';


export default {
  name: 'DashboardAnalysis',
  components: {
    AnalysisSales,
    AnalysisSeniorityUser,
    AnalysisSeniorityAgent,
    AnalysisSeniorityRegion,
    EleChart
  },
  data() {
    return {
      // 本人地域信息
      regionList:[],
      // 地域
      region: null,


      // 用户信息
      user: {},
      // 代理商列表
      agentList: [],
      // 代理商员工列表
      agentUserList: [],
      // 客户分析年月数据
      customerData: [],
      currentYear: '',
      currentMonth: '',
      // 销售量搜索参数
      customerSearch: {
        region: null,
        selectUserId: null,
        agentId: null,
        dataType: '1',
        dataTimeStart: moment().subtract(11, 'months').format('YYYY-MM'),
        dataTimeEnd: moment().format('YYYY-MM')
      },
      // 综合统计数据
      saleroomData: []
    };
  },
  computed: {
    // 综合统计柱状图配置
    saleChartOption() {
      return {
        tooltip: {
          trigger: 'axis'
        },
        xAxis: [
          {
            type: 'category',
            data: this.saleroomData.map(d => d.month),
            /*axisLabel: { // x轴标签样式设置
              rotate: 45, // 设置旋转角度，这里是45度，根据需要调整
              interval: 'auto', // 自动调整标签间隔，避免重叠
              fontSize: 10, // 可选，调整字体大小以适应倾斜后的视觉效果
              overflow: 'truncate' // 可选，超出部分截断处理，避免遮挡其他内容
            }*/
          }
        ],
        yAxis: [
          {
            type: 'value'
          }
        ],
        series: [
          {
            type: 'bar',
            data: this.saleroomData.map(d => d.value)
          }
        ]
      };
    }
  },
  mounted() {
    this.getUser();
    this.getAgentList();
    this.getCustomerData();
    this.getCustomerDataByMonth();
    this.getCurrentYearMonth();
    this.fetchRegionList();
  },

  watch:{
    region() {
      this.customerSearch.region = this.region;
      this.reloadCustomer();
    },

    '$route'(to, from) {
      // 当路由发生变化时，这里会被调用
      if(to.path === '/dashboard/analysis'){
        console.log('路由切换到报表页面', from.path, to.path);
        // 重新加载当前页面
        location.reload();
      }
    },
  },
  methods: {

    // 获取地域信息
    async fetchRegionList() {
      const res = await DashboardApi.findRegionList({});
      this.regionList = res.data;
      // 在组件挂载时设置默认值
      if (this.regionList.length > 0) {
        this.region = this.regionList[0];
      }
    },

    // 加载代理商下拉数据
    async getAgentList() {
      const res = await DashboardApi.findAgentList(this.customerSearch);
      this.agentList = res.data;
    },

    // 获取用户信息
    async getUser() {
      const res = await DashboardApi.getUser();
      this.user = res.data;
      if (this.user.agentId !== '') {
        // 加载代理商员工列表
        const res2 = await WebUserApi.getAgentUserList();
        this.agentUserList = res2.data;
      }
    },
    // 获取客户分析数据
    async getCustomerData() {
      const res = await DashboardApi.customer(this.customerSearch);
      this.customerData = res.data;
    },

    // 条件变化重新加载客户统计数据
    async reloadCustomer() {
      this.getAgentList();// 重新获取代理商数据
      this.getCustomerData();// 重新获取客户分析数据
      this.getCustomerDataByMonth();// 重新获取综合分析数据
    },

    // 条件变化重新加载综合统计数据
    async reloadCustomerByMonth(type) {
      // 校验开始月份和结束月份的间隔是否大于12个月
      if (this.customerSearch.dataTimeStart && this.customerSearch.dataTimeEnd) {
        const start = moment(this.customerSearch.dataTimeStart);
        const end = moment(this.customerSearch.dataTimeEnd);
        if (start > end) {
          this.$message.error('开始月份不得早于结束月份');
          if (type === 1) this.customerSearch.dataTimeStart = '';
          if (type === 2) this.customerSearch.dataTimeEnd = '';
          return;
        }
        const diff = end.diff(start, 'months');
        if (diff > 11) {
          this.$message.error('开始月份和结束月份的间隔不能超过12个月');
          return;
        }
      }

      this.getCustomerDataByMonth();// 重新获取综合分析数据
    },

    /* 获取销售量数据 */
    async getCustomerDataByMonth() {
      const res = await DashboardApi.customerByMonths(this.customerSearch);
      this.saleroomData = res.data;
    },
    getCurrentYearMonth() {
      const now = new Date();
      const year = now.getFullYear();
      const month = (now.getMonth() + 1).toString().padStart(2, '0');
      this.currentYear = `${year}`;
      this.currentMonth = `${month}`;
    },
  }
};
</script>

<style scoped>
/* 统计卡片 */
.analysis-chart-card :deep(.ant-card-body) {
  padding: 16px 22px 12px 22px;
}

.analysis-chart-card-num {
  font-size: 30px;
}

.analysis-chart-card-content {
  height: 40px;
}

.analysis-chart-card :deep(.ant-divider) {
  margin: 12px 0;
}

/* 销售额、访问量 */
.monitor-card-tabs :deep(.ant-tabs-bar) {
  padding: 0;
}

.monitor-card-tabs :deep(.ant-tabs-tab) {
  padding-left: 0px;
  padding-right: 2px;
  margin: 0 !important;
  font-size: 16px;
}

.ant-tabs-ink-bar ant-tabs-ink-bar-animated {
  transform: translate3d(0px, 0px, 0px);

}

.monitor-card-tabs :deep(.ant-tabs-tabpane) {
  padding-bottom: 10px;
}

.demo-monitor-title {
  padding: 6px 20px;
}

.demo-monitor-rank-item {
  padding: 0 20px;
  margin-top: 18px;
}

@media screen and (max-width: 880px) {
  .analysis-tabs-extra {
    display: none;
  }
}

.monitor-count-card :deep(.ant-card-body) {
  padding: 0;
}

.ant-card-grid :deep {
  padding: 20px 15px;
}

/deep/.ant-select-selection-placeholder {
  color: black;
}



.monitor-count-card {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;

  .monitor-count-card-num {
    //margin-left: 5px;
    font-size: 32px;
    line-height: 36px;
  }

  .monitor-count-card-left {
    //margin: 0 5px;
  }

  .monitor-count-card-right {
    //margin-left: 8px;
    min-width: 120px;
  }

  .monitor-count-card-text {
    font-size: 16px;
    margin: 5px 0;
    opacity: 0.8;
  }

  .monitor-count-card-trend {
    font-weight: bold;
    line-height: 26px;

    & > .anticon {
      margin-right: 6px;
    }
  }

  .monitor-count-card-tips {
    position: absolute;
    top: 16px;
    right: 16px;
    cursor: pointer;
    opacity: 0.6;
  }

  .monitor-count-card-title {
    display: flex;
    justify-content: center;
    align-items: center;
  }
}
</style>
